package SGUI

import (
	. "SGEngine2"
	"fmt"
	"github.com/robertkrimen/otto"
	"io/ioutil"
	"os"
	"strconv"
)

var UIScript _UIScript
var ScriptFolder = "../../JavaScript/"

type _UIScript struct {
	JsEngine  *otto.Otto
	globalStr string
}

func (this *_UIScript) Init() {
	this.RunGlobalScript()
	this.ListenGlobalEvent()

	this.JsEngine.Set("AddEvent", func(call otto.FunctionCall) otto.Value {
		n, _ := call.Argument(0).Export()
		eName, _ := call.Argument(1).ToString()

		var em *EventMessage
		gem := n.(IWidget).GetWidgetInfo().Node.Get("EventMessage")
		if gem != nil {
			em = gem.(*EventMessage)
		} else {
			em = &EventMessage{}
		}
		eType, _ := call.Argument(3).ToInteger()
		eId, _ := call.Argument(4).ToString()
		em.RegisterEvent(int(eType), func(em *EventMessage, x int, y int) {
			_, err := call.Argument(2).Object().Call(eName, call.Argument(0).Object(), eId)
			if err != nil {
				fmt.Println(err)
			}
		})

		if gem == nil {
			n.(IWidget).GetWidgetInfo().Node.Add(em)
		}
		return otto.Value{}
	})

	this.JsEngine.Set("EventCatch", func(call otto.FunctionCall) otto.Value {
		node, _ := call.Argument(0).Export()
		x, _ := call.Argument(1).ToInteger()
		y, _ := call.Argument(2).ToInteger()
		etype, _ := call.Argument(3).ToInteger()
		b := EventManager.EventCatch(RootView.ViewScene.RootNode, node.(*Node), int(x), int(y), int(etype))
		rb, _ := otto.ToValue(b)
		return rb
	})
}

func (this *_UIScript) RunGlobalScript() {
	f, err := os.Open(ScriptFolder + "SGUIGlobal.js")
	if err != nil {
		fmt.Println(err)
	}
	bs, _ := ioutil.ReadAll(f)
	UIScript.JsEngine = otto.New()
	_, err2 := UIScript.JsEngine.Run(string(bs))
	if err2 != nil {
		fmt.Println(err2)
	}
}

func (this *_UIScript) ListenGlobalEvent() {
	EventManager.AddGlobalEvent(GEVENT_MOUSEDOWN, func(p0, p1, p2, p3 int) {
		RunStr := `Global.event.GlobalEventHandler(0,` + strconv.Itoa(p0) + `,` + strconv.Itoa(p1) + `,` + strconv.Itoa(p2) + `,` + strconv.Itoa(p3) + `)`
		_, err := UIScript.JsEngine.Run(RunStr)
		if err != nil {
			fmt.Println(err)
		}
	})
}
